package com.tudouji.project.flow.controller;

import com.alibaba.fastjson.JSONObject;
import com.flow.service.pojo.flow.FlowTempNode;
import com.flow.service.process.service.IFlowTempNodeService;
import com.tudouji.common.utils.poi.ExcelUtil;
import com.tudouji.framework.aspectj.lang.annotation.Log;
import com.tudouji.framework.aspectj.lang.enums.BusinessType;
import com.tudouji.framework.web.controller.BaseController;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.TableDataInfo;
import com.tudouji.project.bill.service.ISellformService;
import com.tudouji.project.flow.domain.BasePojo;
import com.tudouji.project.flow.domain.Flowconditions;
import com.tudouji.project.flow.domain.Flowtempnode;
import com.tudouji.project.flow.domain.Operationlogs;
import com.tudouji.project.flow.service.BasePojoService;
import com.tudouji.project.flow.service.IFlowconditionsService;
import com.tudouji.project.flow.service.IFlowtempnodeService;
import com.tudouji.project.flow.service.IOperationlogsService;
import com.tudouji.project.harvest.service.IFreightorderService;
import com.tudouji.project.harvest.service.IProcurementcontractService;
import com.tudouji.project.system.domain.Tuser;
import com.tudouji.project.system.service.ITuserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 流程节点Controller
 *
 * @author wf
 * @date 2021-04-01
 */
@RestController
@RequestMapping("/flow/flowtempnode")
public class FlowtempnodeController extends BaseController
{
    @Autowired
    private IFlowtempnodeService flowtempnodeService;
    @Autowired
    private IFlowTempNodeService flowTempNodeService;
    @Autowired
    private IOperationlogsService operationlogsService;
    @Autowired
    private IFlowconditionsService conditionService;
    @Autowired
    private IProcurementcontractService procurementcontractService;
    @Autowired
    private IFreightorderService freightorderService;
    @Autowired
    private ISellformService sellformService;
    @Autowired
    private BasePojoService basePojoService;
    @Autowired
    private ITuserService tuserService;

//    /**
//     * 查询流程节点列表
//     */
//    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(FlowTempNode flowtempnode)
//    {
//        startPage();
//        List<FlowTempNode> list = flowTempNodeService.selectFlowTempNodeList(flowtempnode);
//        return getDataTable(list);
//    }

        /**
     * 查询流程节点列表
     */
    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:list')")
    @GetMapping("/list")
    public TableDataInfo list(FlowTempNode flowtempnode)
    {
        startPage();
        List<FlowTempNode> list = flowtempnodeService.selectFlowtempnodeList(flowtempnode);
        return getDataTable(list);
    }



    /**
     * 导出流程节点列表
     */
    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:export')")
    @Log(title = "流程节点", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FlowTempNode flowtempnode)
    {
        List<FlowTempNode> list = flowtempnodeService.selectFlowtempnodeList(flowtempnode);
        ExcelUtil<FlowTempNode> util = new ExcelUtil<>(FlowTempNode.class);
        return util.exportExcel(list, "flowtempnode");
    }

//    /**
//     * 获取流程节点详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:query')")
//    @GetMapping(value = "/{guid}")
//    public AjaxResult getInfo(@PathVariable("guid") String guid)
//    {
//        return AjaxResult.success(flowtempnodeService.selectFlowtempnodeById(guid));
//    }

    /**
     *通过id查询流程节点
     * @param id
     * @return
     */
    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getFlowtempnodeInfo(@PathVariable("id") Long id)
    {

        return AjaxResult.success(flowtempnodeService.selectFlowtempnodeByid(id));
    }


    /**
     * 新增流程节点
     */
    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:add')")
    @Log(title = "流程节点", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FlowTempNode flowtempnode)
    {
        return toAjax(flowtempnodeService.insertFlowTempnode(flowtempnode));
    }


//    /**
//     * 新增流程节点
//     */
//    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:add')")
//    @Log(title = "流程节点", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody FlowTempNode flowtempnode)
//    {
//        return toAjax(flowTempNodeService.insertFlowTempNode(flowtempnode));
//    }


    /**
     * 修改流程节点
     */
    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:edit')")
    @Log(title = "流程节点", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FlowTempNode flowtempnode)
    {
        return toAjax(flowtempnodeService.updateFlowTempnode(flowtempnode));
    }


//    /**
//     * 修改流程节点
//     */
//    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:edit')")
//    @Log(title = "流程节点", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody FlowTempNode flowtempnode)
//    {
//        return toAjax(flowTempNodeService.updateFlowTempNode(flowtempnode));
//    }

    /**
     * 删除流程节点
     */
    @PreAuthorize("@ss.hasPermi('flow:flowtempnode:remove')")
    @Log(title = "流程节点", businessType = BusinessType.DELETE)
	@DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable Long[] guids)
    {
        return toAjax(flowTempNodeService.deleteFlowTempNodeByIds(guids));
    }

    /**
     * 获取销售/采收合同 流程节点
     */
    @RequestMapping(value = "/getSaleFlowNodes", method = RequestMethod.GET)
    public AjaxResult getSaleFlowNodes(@RequestParam("guid") String guid, @RequestParam(value = "srguid", required = false) String srguid
            , @RequestParam(value = "departid", required = false) String departid) {
        JSONObject json = new JSONObject();
        try {
            Flowtempnode node = new Flowtempnode();
            node.setOrderid(guid);
            // 已操作过的节点及操作员
            List<Flowtempnode> donenodes = flowtempnodeService.getDoneNodes(node);
            // 获取未操作节点及授权操作员
            if (donenodes.size() > 0) {
                // 获取操作日志
                for (Flowtempnode no : donenodes) {
                    Operationlogs opl = new Operationlogs();
                    opl.setGuid(no.getOptlogid());
                    opl = operationlogsService.findDetail(opl);
                    no.setLogs(opl);
                }

                //判断最后一个操作是否是结束节点
                Flowtempnode fp=flowtempnodeService.selectFlowtempnodeById(donenodes.get(donenodes.size()-1).getGuid());
                if(fp.getNodetype()!=4){
                    String flowid = "";
                    Integer sort = 0;
                    String doneLastNodeid = "";
                    for (int i = donenodes.size() - 1; i > -1; i--) {
                        String nodeid = donenodes.get(i).getGuid();
                        Flowtempnode nd = flowtempnodeService.selectFlowtempnodeById(nodeid);
                        if (nd != null && nd.getFlag() != null && nd.getFlag() == 1) {
                            doneLastNodeid = nd.getGuid();
                            flowid = nd.getFlowtempid();
                            sort = nd.getSort();
                            break;
                        }
                    }
                    // 获取已操作的最后一个节点的排序
                    node.setSort(sort);
                    node.setFlowtempid(flowid);
                    node.setSrguid(srguid);
                    node.setDepartid(departid);
                    // 获取未操作节点及授权操作员
                    List<Flowtempnode> unDonodes = flowtempnodeService.getUndoNodes(node);

                    BasePojo base= sellformService.selectSellformOldByGuid(guid);

                   /* if(base==null){
                        base= procurementcontractService.selectProcurementcontractById(guid);
                    }*/
                   /*if(base==null){
                        base=freightorderService.selectFreightorderById(guid);
                    }*/

                    // 查询已操作的最后一个节点是否有条件
                    Flowconditions cd = new Flowconditions();
                    cd.setNodeguid(doneLastNodeid);
                    List<Flowconditions> cds = conditionService.selectFlowconditionsList(cd);

                    // 获取满足条件的nodeid
                    String cdNodeid = "";
                    if (cds.size() > 0) {
                        label: for (Flowconditions fc : cds) {
                            base.setCondition(fc.getConditions());
                            Integer count = basePojoService.getCounts(base);
                            if (count > 0) {
                                cdNodeid = fc.getNextnodeid();
                                break label;
                            }
                        }
                    }

                    List<Flowtempnode> newUnDonodes = new ArrayList<>();
                    //设置一个不存在的默认值，用作最后一个已操作节点有条件成立，但是第一个未操作节点不成立的时候 跳过处理下一个未处理节点
                    String nextNodeid = "nodeid";
                    for (int i = 0; i < unDonodes.size(); i++) {
                        if (StringUtils.isBlank(cdNodeid)&&i == 0) {
                            newUnDonodes.add(unDonodes.get(i));
                            nextNodeid=getNextNodeid(unDonodes.get(i).getGuid(), base);
                        }else if(StringUtils.isNotBlank(cdNodeid)&&cdNodeid.equals(unDonodes.get(i).getGuid())){
                            newUnDonodes.add(unDonodes.get(i));
                            nextNodeid=getNextNodeid(unDonodes.get(i).getGuid(), base);
                        }else{
                            if (unDonodes.get(i).getGuid().equals(nextNodeid)) {
                                newUnDonodes.add(unDonodes.get(i));
                                nextNodeid=getNextNodeid(unDonodes.get(i).getGuid(), base);
                            }else if(StringUtils.isBlank(nextNodeid)){
                                newUnDonodes.add(unDonodes.get(i));
                                nextNodeid=getNextNodeid(unDonodes.get(i).getGuid(), base);
                            }
                        }
                    }

                    for(Flowtempnode fn:newUnDonodes){
                        if(fn.getPermission().equals("0")){
                            Tuser user=tuserService.selectTuserById(base.getOperatorid());
                            List<Tuser> us=new ArrayList<>();
                            us.add(user);
                            fn.setOperators(us);
//							fn.setOperators(donenodes.get(0).getOperators());
                        }
                        if(fn.getNodetype()==4){
                            fn.setStatus(1);
                        }
                    }
                    donenodes.addAll(newUnDonodes);
                }
            }
            return AjaxResult.success(donenodes);
        } catch (Exception e) {
            json.put("msg", "error");
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
    public String getNextNodeid(String nodeid, BasePojo base){
        try {
            Flowconditions condition = new Flowconditions();
            condition.setNodeguid(nodeid);
            List<Flowconditions> conditions = conditionService.selectFlowconditionsList(condition);
            if (conditions.size() > 0) {
                for (Flowconditions fd : conditions) {
                    base.setCondition(fd.getConditions());
                    Integer count = basePojoService.getCounts(base);
                    if (count > 0) {
                        return fd.getNextnodeid();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping("/getFlowtempnode")
    public AjaxResult getFlowtempnode(FlowTempNode flowtempnode)
    {
        List<FlowTempNode> list = flowtempnodeService.selectFlowtempnodeList(flowtempnode);
        return AjaxResult.success(list);
    }
}
